package j.nawks.wx.api.message.convert;

import j.nawks.wx.api.message.support.EventType;
import j.nawks.wx.api.message.support.MessageType;
import j.nawks.wx.api.utils.ClassUtils;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TypeConvertProcess {
	private Map<Type, Convert> typeConverts;
	private static Convert defaultConvert = new StringTypeConvert();

	private static TypeConvertProcess instance = new TypeConvertProcess();

	public static TypeConvertProcess getInstance() {
		return instance;
	}

	private TypeConvertProcess() {
		this._init();
	}

	private void _init() {
		this.typeConverts = new HashMap<Type, Convert>();
		registerType(MessageType.class, MessageTypeConvert.class);
		registerType(Date.class, TimeTypeConvert.class);
		registerType(EventType.class, EventTypeConvert.class);
		registerType(String.class, StringTypeConvert.class);
		registerType(Long.class, LongTypeConvert.class);
		registerType(BigDecimal.class, BigDecimalTypeConvert.class);
	}

	private void registerType(Class<?> type, Class<? extends Convert> convert) {
		this.typeConverts.put(type, (Convert) ClassUtils.instance(convert));
	}

	public Object getValue(Type type, String plainTextValue) {
		if (plainTextValue == null)
			return null;

		Convert convert = this.typeConverts.get(type);
		if (convert == null) {
			convert = defaultConvert;
		}
		return convert.convert(plainTextValue);
	}
}
